package com.dsg.javaconfig;

import com.dsg.utils.DbRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Resource
    private DbRealm dbRealm;

    @Bean
    public ShiroFilterFactoryBean shiroFilter(){
        ShiroFilterFactoryBean sf = new ShiroFilterFactoryBean();
        sf.setLoginUrl("/login");
        Map<String,String> map = new HashMap<String,String>();
        map.put("/logout","logout");
        map.put("/css/**","anon");
        map.put("/dist/**","anon");
        map.put("/img/**","anon");
        map.put("/js/**","anon");
        map.put("/static/**","anon");
        map.put("/webjars/**","anon");
        map.put("/login","anon");
        map.put("/**","authc");
        sf.setFilterChainDefinitionMap(map);
        sf.setSecurityManager(securityManager());
        return  sf;
    }

    @Bean
    public DefaultWebSecurityManager securityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(dbRealm);
        return securityManager;
    }

    @Bean
    public HashedCredentialsMatcher credentialsMatcher(){
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("md5");
        credentialsMatcher.setHashIterations(1);
        return credentialsMatcher;
    }
}
